package controller.user_management;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.provider.ContactsContract;
import android.util.Log;
import android.widget.Toast;

import com.trek2000.android.enterprise.R;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import adapter.user_management.SuggestUserInInviteUserToCompanyAdapter;
import model.user_management.UserInfoFromContactItem;
import ui.activity.user_managament.InviteUserToCompany;
import ui.fragment.custom.camera.CameraReviewFragment;

/**
 * Created by trek2000 on 9/9/2014.
 */
public class GetUserInfoFromContactAsync extends AsyncTask<String, Integer, Boolean> {

    /**
     * Data section
     */
    public  static  ArrayList<UserInfoFromContactItem> mAlUserInfoFromContact = new ArrayList<>();
    /**
     * String section
     */
     private Boolean CONTACT_IS_EMPTY = false;
    /**
     * View section
     */

    /**
     * The other sections
     */
    private Context mContext;
    // declare the dialog as a member field of your activity

    public GetUserInfoFromContactAsync(Context mContext) {
        this.mContext = mContext;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Boolean doInBackground(String... sUrl) {
        try {
            mAlUserInfoFromContact = getContacts();
            if (!mAlUserInfoFromContact.isEmpty()) return true;
            else {
                CONTACT_IS_EMPTY = true;
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);

        if (!result) {
            if (CONTACT_IS_EMPTY) {
                Toast.makeText(mContext.getApplicationContext(),
                        mContext.getString(R.string.toast_empty_contact),
                        Toast.LENGTH_LONG).show();
                CONTACT_IS_EMPTY = false;
            }
        } else {
            InviteUserToCompany.suggestUserInInviteUserToCompanyAdapter  = new SuggestUserInInviteUserToCompanyAdapter(
                    mContext, R.layout.simple_list_item_in_suggest_user_in_invite_user_to_company_activity,
                    mAlUserInfoFromContact
            );
            InviteUserToCompany.mLvSuggestUserInInviteUserToCompany.setAdapter(
                    InviteUserToCompany.suggestUserInInviteUserToCompanyAdapter
            );
        }
    }

    public ArrayList<UserInfoFromContactItem> getContacts() {
        ArrayList<UserInfoFromContactItem> mAlUserInfoFromContact = new ArrayList<>();
        final String[] projection = new String[] { ContactsContract.RawContacts.CONTACT_ID, ContactsContract.RawContacts.DELETED };

        @SuppressWarnings("deprecation")
        final Cursor rawContacts = ((Activity)mContext).managedQuery(ContactsContract.RawContacts.CONTENT_URI, projection, null, null, null);

        final int contactIdColumnIndex = rawContacts.getColumnIndex(ContactsContract.RawContacts.CONTACT_ID);
        final int deletedColumnIndex = rawContacts.getColumnIndex(ContactsContract.RawContacts.DELETED);

        if (rawContacts.moveToFirst()) {
            while (!rawContacts.isAfterLast()) {
                final int contactId = rawContacts.getInt(contactIdColumnIndex);
                final boolean deleted = (rawContacts.getInt(deletedColumnIndex) == 1);

                if (!deleted) {
//                    HashMap<String, Object> contactInfo = new HashMap<String, Object>() {
//                        {
//                            put("contactId", "");
//                            put("name", "");
//                            put("email", "");
//                            put("address", "");
//                            put("photo", "");
//                            put("phone", "");
//                        }
//                    };

//                    contactInfo.put("contactId", "" + contactId);
//                    contactInfo.put("name", getName(contactId));
//                    contactInfo.put("email", getEmail(contactId));
//                    contactInfo.put("photo", getPhoto(contactId) != null ? getPhoto(contactId) : "");
//                    contactInfo.put("address", getAddress(contactId));
//                    contactInfo.put("phone", getPhoneNumber(contactId));
//                    contactInfo.put("isChecked", "false");
//                    Log.i("", "getEmail(contactId) " + getEmail(contactId));
//                    Log.i("","getPhoto(contactId) " +  getPhoto(contactId));
//                    contacts.add(contactInfo);
                    // check email empty and photo null
                    if (!"".equals(getEmail(contactId))) {
                        mAlUserInfoFromContact.add(
                                new UserInfoFromContactItem(getName(contactId),
                                        getEmail(contactId),
                                        getPhoto(contactId))
                        );
                    }
                }
                rawContacts.moveToNext();
            }
        }
        rawContacts.close();
        return mAlUserInfoFromContact;
    }

    private String getName(int contactId) {
        String name = "";
        final String[] projection = new String[] { ContactsContract.Contacts.DISPLAY_NAME };

        final Cursor contact = ((Activity)mContext).managedQuery(ContactsContract.Contacts.CONTENT_URI, projection, ContactsContract.Contacts._ID + "=?", new String[]{String.valueOf(contactId)}, null);

        if (contact.moveToFirst()) {
            name = contact.getString(contact.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            contact.close();
        }
        contact.close();
        return name;

    }

    private String getEmail(int contactId) {
        String emailStr = "";
        final String[] projection = new String[] { ContactsContract.CommonDataKinds.Email.DATA, // use
                // Email.ADDRESS
                // for API-Level
                // 11+
                ContactsContract.CommonDataKinds.Email.TYPE };

        final Cursor email = ((Activity)mContext).managedQuery(ContactsContract.CommonDataKinds.Email.CONTENT_URI, projection, ContactsContract.Data.CONTACT_ID + "=?", new String[]{String.valueOf(contactId)}, null);

        if (email.moveToFirst()) {
            final int contactEmailColumnIndex = email.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA);
            // only get one mail (can get many mail)
//            while (!email.isAfterLast()) {
                emailStr = emailStr + email.getString(contactEmailColumnIndex);
//                email.moveToNext();
//            }
        }
        email.close();
        return emailStr;
    }

    private Bitmap getPhoto(int contactId) {
        Bitmap photo = null;
        final String[] projection = new String[] { ContactsContract.Contacts.PHOTO_ID };

        final Cursor contact = ((Activity)mContext).managedQuery(ContactsContract.Contacts.CONTENT_URI, projection, ContactsContract.Contacts._ID + "=?", new String[]{String.valueOf(contactId)}, null);

        if (contact.moveToFirst()) {
            final String photoId = contact.getString(contact.getColumnIndex(ContactsContract.Contacts.PHOTO_ID));
            if (photoId != null) {
                photo = getBitmap(photoId);
            } else {
                photo = null;
            }
        }
        contact.close();
        return photo;
    }

    private Bitmap getBitmap(String photoId) {
        final Cursor photo = ((Activity)mContext).managedQuery(ContactsContract.Data.CONTENT_URI, new String[] { ContactsContract.CommonDataKinds.Photo.PHOTO }, ContactsContract.Contacts.Data._ID + "=?", new String[] { photoId }, null);

        final Bitmap photoBitmap;
        if (photo.moveToFirst()) {
            byte[] photoBlob = photo.getBlob(photo.getColumnIndex(ContactsContract.CommonDataKinds.Photo.PHOTO));
            photoBitmap = BitmapFactory.decodeByteArray(photoBlob, 0, photoBlob.length);
        } else {
            photoBitmap = null;
        }
        photo.close();
        return photoBitmap;
    }

    private String getAddress(int contactId) {
        String postalData = "";
        String addrWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
        String[] addrWhereParams = new String[] { String.valueOf(contactId), ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE };

        Cursor addrCur = ((Activity)mContext).managedQuery(ContactsContract.Data.CONTENT_URI, null, addrWhere, addrWhereParams, null);

        if (addrCur.moveToFirst()) {
            postalData = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS));
        }
        addrCur.close();
        return postalData;
    }

    private String getPhoneNumber(int contactId) {

        String phoneNumber = "";
        final String[] projection = new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.TYPE, };
        final Cursor phone = ((Activity)mContext).managedQuery(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, ContactsContract.Data.CONTACT_ID + "=?", new String[]{String.valueOf(contactId)}, null);

        if (phone.moveToFirst()) {
            final int contactNumberColumnIndex = phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA);

            while (!phone.isAfterLast()) {
                phoneNumber = phoneNumber + phone.getString(contactNumberColumnIndex) + ";";
                phone.moveToNext();
            }
        }
        phone.close();
        return phoneNumber;
    }
}
